package com.xmotor.test_cookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description cookie相关工具类
 * @Author Dang Xianyue
 * @Date 2020-10-19 09:13
 * @Version 1.0
 */
public class CookieUtil {

    private CookieUtil() {
    }

    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
//        cookie.setSecure(true);//安全限制，非https开头的域名无法发送cookie
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, String name, String value, String domain) {
        Cookie cookie = new Cookie(name, value);
        cookie.setDomain(domain);
        cookie.setPath("/");
//        cookie.setSecure(true);
        response.addCookie(cookie);
    }

    public static Map<String, String> ReadCookieMap(HttpServletRequest request) {
        Map<String, String> cookieMap = new HashMap();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            Cookie[] var3 = cookies;
            int var4 = cookies.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                Cookie cookie = var3[var5];
                cookieMap.put(cookie.getName(), cookie.getValue());
            }
        }

        return cookieMap;
    }

    public static String getCookieValueByName(HttpServletRequest request, String name) {
        Map<String, String> cookieMap = ReadCookieMap(request);
        if (cookieMap.containsKey(name)) {
            String cookieValue = (String)cookieMap.get(name);
            return cookieValue;
        } else {
            return null;
        }
    }
}
